<template>
  <div>
    <div class="search">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <!-- {{ form }} -->
        <el-row>
          <el-col :span="4">
            <el-form-item>
              <el-button @click="toAdd()" type="primary">新增</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <!-- <el-form-item>
              <el-select clearable v-model="form.role_id" placeholder="请选择用户角色">
                <el-option v-for="item in categories" :key="item.id" :label="item.role_name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-input clearable v-model="form.realname" placeholder="用户姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </div>

    <!-- 表格开始 -->
    <div class="table">
      <el-table :data="userData" style="width: 100% ;">
        <el-table-column type="index" :index="1" label="序号" width="100" align="center">
        </el-table-column>
        <el-table-column label="用户名" width="120">
          <template v-slot="scope">
            <div>
              {{ scope.row.username }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="120">
          <template v-slot="scope">
            <div>
              <div>{{ scope.row.realname }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="120">
          <template v-slot="scope">
            <div>
              <div>{{ scope.row.role_name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="性别" width="120">
          <template v-slot="scope">
            <div>
              <div>{{ scope.row.gender === 'male' ? '男' : '女' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="生日" width="120" align="center">
          <template v-slot="scope">
            <div>
              <div>{{ Number(scope.row.birth) | fmtDate }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="联系方式" align="center">
          <template v-slot="scope">
            <div>
              <div>{{ scope.row.telephone }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template v-slot="scope">
            <div>
              <div>{{ scope.row.status }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center">
          <template v-slot="scope">
            <div>
              <el-link @click="toEdit(scope.row)" :underline="false" type='success'>修改权限</el-link><br>
              <el-link :underline="false" type="danger" @click="toDelete(scope.row.id)">删除用户</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page" style="margin-top:15px">
      <el-pagination hide-on-single-page background @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="params.page" :page-sizes="[9, 18, 27, 36]"
        :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 模态框 -->
    <el-dialog title="新增用户" :visible.sync="visible">
      <!-- {{ form2 }} -->
      <el-form :model="form2" ref="ruleForm">
        <el-form-item label="用户名" label-width="80px">
          <el-input v-model="form2.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" label-width="80px">
          <el-input type="password" v-model="form2.password"></el-input>
        </el-form-item>
        <el-form-item label="选择角色" label-width="80px">
          <el-select clearable v-model="form2.role_id" placeholder="请选择用户角色">
            <el-option v-for="item in categories" :key="item.id" :label="item.role_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="confirmAdd()" type="primary">确认添加</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增用户" :visible.sync="visible2">
      <el-form>
        <!-- {{ role }} -->
        <el-form-item label="用户名" label-width="80px">
          <el-input v-model="role.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="选择角色" label-width="80px">
          <el-select clearable v-model="role.role_id" placeholder="请选择用户角色">
            <el-option v-for="item in categories" :key="item.id" :label="item.role_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-button @click="confirmUpdate()" type="primary">确认更改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { get } from '@/utils/request'
import { post } from '@/utils/request'
export default {
  data() {
    return {
      // 根据条件查询表单对象
      form: {},
      form2: {},
      // 更改权限
      role: {},
      // 保存所有栏目
      categories: [],
      // 课程数据源
      userData: [],
      // 分页对象
      params: {
        page: 1,
        pageSize: 9
      },
      // 数据总条数
      total: 0,
      // 点击审核接收当前被点击审核对象
      rowArticle: {},
      // 控制模态框显示与隐藏变量
      visible: false,
      visible2: false
    }
  },
  methods: {
    async confirmUpdate() {
      let res = await post('/user/updateUserRole', this.role)
      // console.log(res);
      if (res.status === 200) {
        this.getUser(); // 刷新用户列表
        this.$message({
          type: 'success',
          message: '成功更改角色' // 确保服务器返回的消息是这个
        });
      } else {
        // 处理非 200 状态码的情况
        this.$message({
          type: 'error',
          message: res.message || '更改失败' // 使用服务器返回的消息，如果没有则使用默认消息
        });
      }
      this.visible2 = false; // 关闭模态框
      this.role = {}; // 重置表单
    },
    toEdit(info) {
      this.role = info
      this.visible2 = true
      this.role.user_id = info.id
    },
    async confirmAdd() {
      try {
        let res = await post('/user/addUserWithRole', this.form2);
        if (res.status === 200) {
          this.getUser(); // 刷新用户列表
          this.$message({
            type: 'success',
            message: '用户添加成功并设置角色' // 确保服务器返回的消息是这个
          });
        } else {
          // 处理非 200 状态码的情况
          this.$message({
            type: 'error',
            message: res.message || '添加用户失败' // 使用服务器返回的消息，如果没有则使用默认消息
          });
        }
      } catch (error) {
        // 处理请求异常
        console.error('Error adding user:', error);
        this.$message({
          type: 'error',
          message: error.message || '添加用户时发生错误' // 使用错误对象的消息，如果没有则使用默认消息
        });
      } finally {
        this.visible = false; // 关闭模态框
        this.form2 = {}; // 重置表单
      }
    },
    toAdd() {
      this.visible = true
    },
    // 删除用户
    toDelete(id) {
      console.log(id);
      this.$confirm('此操作将删除此用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await get('/user/deleteById', { id })
        if (res.status === 200) {
          this.getUser()
          // console.log(res);
          this.$message({
            type: 'success',
            message: res.message
          });
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async getRoleCategory() {
      let res = await get('/user/getAllRoles')
      // console.log(res);
      this.categories = res.data
    },
    // 分页多条件获取课程信息
    async getUser() {
      // 将分页对象属性和条件对象属性传给后端
      let temp = {
        ...this.params,//必传
        ...this.form
      }
      // 判断条件是否存在 存在传给后端  不存在删除条件
      for (let key in temp) {
        if (!temp[key]) {
          delete temp[key]
        }
      }
      let res = await get('user/pageQueryFind', temp)
      console.log(res.data.list);
      console.log(res);

      this.userData = res.data.list;
      this.total = res.data.total
    },
    // 每页大小触发的方法  5条一页变成10条一夜
    handleSizeChange(pageSize) {
      // pageSize由5改为10
      this.params.page = 1
      this.params.pageSize = pageSize;
      this.getUser()
    },
    // 页面发生改变触发方法
    handleCurrentChange(page) {
      this.params.page = page;
      this.getUser()
    },
  },
  // 监听form
  watch: {
    // form(){
    //   this.getArticle()
    // }
    form: {
      handler() {
        this.params.page = 1;
        this.getUser()
      },
      deep: true
    }
  },
  created() {
    this.getRoleCategory()
    this.getUser()
  },
}
</script>